#include <set>
#include <vector>

using namespace std;

class Solution {
public:
    int longestSubarray(vector<int>& nums, int limit) {
        if (nums.size() == 1) {
            return 1;
        }
        multiset<int> set;
        set.insert(nums[0]);
        int begin = 0;
        int ans = 0;
        for (int i = 1; i < nums.size(); ) {
            if (set.empty() || (abs(nums[i] - *set.begin()) <= limit && abs(nums[i] - *set.rbegin()) <= limit)) {
                set.insert(nums[i]);
                i++;
                ans = max(ans, i - begin);
            } else {
                set.erase(set.find(nums[begin]));
                begin++;
            }
        }
        return ans;
    }
};